#include <iostream>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>


void Usge(const char* args)
{
  std::cout << "please input \n\t";
  std::cout << args << " + ip + port\n";
}

int main(int argc, char* argv[])
{
  if(argc != 3) 
  {
    Usge(argv[0]);
    exit(-1);
  }

  int port = htons(atoi(argv[2]));
  int sock = socket(AF_INET, SOCK_DGRAM, 0);
  struct sockaddr_in serveraddr;
  serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
  serveraddr.sin_family = AF_INET;
  serveraddr.sin_port = port;
  
  while(1)
  {
    char buffer[] = "hello world";
    int ret = sendto(sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&serveraddr, sizeof(serveraddr));
    if(ret == sizeof(buffer) - 1)
    {
      char str[1024];
      int ret = recv(sock, str, sizeof(str) - 1, 0);
      str[ret] = '\0';
      std::cout << "recv : " << str << std::endl;
    }
    else
    {
      std::cout << "recv error\n";
      break;
    }
    sleep(1);
  }
  return 0;
}
